import React, { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import style from './TransferPage.module.css';

export default function TransferPage() {
  const navigate = useNavigate();
  const location = useLocation();
  const { targetUserId = '', targetUserName = '好友', targetUserAvatar = '', ws, userId = '', userName = '' } = location.state || {};

  const [step, setStep] = useState('input'); // input | success | wait
  const [amount, setAmount] = useState('');
  const [remark, setRemark] = useState('');
  const [showCopied, setShowCopied] = useState(false);
  const [transferTime] = useState(new Date());

  // 数字键盘输入
  const handleKey = (val) => {
    if (val === 'del') {
      setAmount(a => a.slice(0, -1));
    } else if (val === '.' && amount.includes('.')) {
      return;
    } else if (val === '.' && amount === '') {
      setAmount('0.');
    } else if (val === '.' || /^[0-9]$/.test(val)) {
      if (amount.length < 8) setAmount(a => a + val);
    }
  };

  // 确认转账
  const handleTransfer = () => {
    if (!amount || isNaN(Number(amount)) || Number(amount) <= 0) return;
    setStep('success');
    setTimeout(() => setStep('wait'), 1200);
    // 聊天联动：可在这里通过 WebSocket 发送转账消息
    // ...
  };

  // 复制功能
  const handleCopy = () => {
    navigator.clipboard.writeText(amount).then(() => {
      setShowCopied(true);
      setTimeout(() => setShowCopied(false), 1200);
    });
  };

  // 完成/收款
  const handleDone = () => {
    // 发送转账消息
    if (ws && ws.readyState === 1) {
      const transferMsg = {
        type: 'transfer',
        senderId: userId,
        senderName: userName,
        receiverId: targetUserId,
        receiverName: targetUserName,
        amount: Number(amount).toFixed(2),
        remark,
        msgId: Date.now(),
        timestamp: new Date().toISOString()
      };
      ws.send(JSON.stringify(transferMsg));
    }
    navigate(-1); // 返回聊天页
  };

  // UI
  return (
    <div className={style.transferPageWrap}>
      {/* 顶部栏 */}
      <div className={style.header}>
        <button className={style.backBtn} onClick={() => navigate(-1)}>&lt;</button>
        <span className={style.headerTitle}>转账给 <span style={{fontWeight:600}}>{targetUserName}</span></span>
        <img src={targetUserAvatar || '/微信头像.jpg'} alt="avatar" className={style.avatar} />
      </div>
      {/* 步骤内容 */}
      {step === 'input' && (
        <div className={style.inputStep}>
          <div className={style.label}>转账金额</div>
          <div className={style.amountInputRow}>
            <span className={style.yuan}>¥</span>
            <input
              className={style.amountInput}
              type="text"
              value={amount}
              readOnly
              placeholder="0.00"
              inputMode="decimal"
            />
            <button className={style.copyBtn} onClick={handleCopy}>复制</button>
          </div>
          <div className={style.remarkRow}>
            <input
              className={style.remarkInput}
              type="text"
              value={remark}
              onChange={e => setRemark(e.target.value)}
              placeholder="添加转账说明（选填）"
              maxLength={20}
            />
          </div>
          {/* 数字键盘 */}
          <div className={style.keypad}>
            {[1,2,3,4,5,6,7,8,9,'.',0,'del'].map((k, i) => (
              <button
                key={i}
                className={k==='del'?style.keyDel:style.keyBtn}
                onClick={() => handleKey(k==='del'?'del':k.toString())}
                aria-label={k==='del'?'删除':k}
              >
                {k==='del'?'⌫':k}
              </button>
            ))}
            <button
              className={style.transferBtn}
              disabled={!amount || isNaN(Number(amount)) || Number(amount)<=0}
              onClick={handleTransfer}
            >转账</button>
          </div>
          {/* 复制提示 */}
          {showCopied && <div className={style.copiedToast}><span>✔</span> 已复制</div>}
        </div>
      )}
      {step === 'success' && (
        <div className={style.successStep}>
          <div className={style.successIconRow}>
            <span className={style.successIcon}>✔</span>
            <span className={style.successText}>支付成功</span>
          </div>
          <div className={style.successAmount}>待{targetUserName}确认收款</div>
          <div className={style.successMoney}>¥ {Number(amount).toFixed(2)}</div>
          <button className={style.doneBtn} onClick={handleDone}>完成</button>
        </div>
      )}
      {step === 'wait' && (
        <div className={style.waitStep}>
          <div className={style.waitIconRow}>
            <span className={style.waitIcon}>🕒</span>
          </div>
          <div className={style.waitText}>待你收款</div>
          <div className={style.waitMoney}>¥ {Number(amount).toFixed(2)}</div>
          <div className={style.waitTimeRow}>
            <span className={style.waitTimeLabel}>转账时间</span>
            <span className={style.waitTime}>{transferTime.toLocaleString()}</span>
          </div>
          <button className={style.receiveBtn} onClick={handleDone}>收款</button>
          <div className={style.waitTip}>1天内未确认，将退还给对方。</div>
        </div>
      )}
    </div>
  );
} 